import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:pornhub_app/http/http_service.dart';
import 'package:pornhub_app/model/sys_site_domain_manager_model/sys_site_domain_manager_model.dart';
import 'package:pornhub_app/sys_station_model/sys_station_model.dart';

class HomePageController extends GetxController {
  final tabInitIndex = 0.obs;

  final stationList = <SysStationModel>[].obs;

  final siteDomain = ''.obs;

  final _isFetchStationListIng = false.obs;

  void changeTab(int index) {
    tabInitIndex.value = index;
  }

  @override
  void onInit() {
    super.onInit();
    final tab = Get.parameters['home_tab_index'] ?? '0';
    tabInitIndex.value = int.parse(tab);
    if (stationList.isEmpty && !_isFetchStationListIng.value) {
      _initStationList();
    }
    if (siteDomain.isEmpty) {
      _initSiteDomain();
    }
  }

  _initStationList() async {
    try {
      _isFetchStationListIng.value = true;
      List<SysStationModel> res = await httpInstance.get(
        url: "sys/station/list",
        queryMap: {
          'type': 1,
        },
        complete: SysStationModel.fromJson,
      );

      if (res.isNotEmpty) {
        stationList.value = res;
      }
    } catch (e) {
      debugPrint(e.toString());
    } finally {
      _isFetchStationListIng.value = false;
    }
  }

  _initSiteDomain() async {
    SysSiteDomainManagerModel res =
        await httpInstance.get<SysSiteDomainManagerModel>(
      url: "sys/siteDomain",
      complete: SysSiteDomainManagerModel.fromJson,
    );
    if (res.domain != null) {
      siteDomain.value = res.domain ?? '';
    }
  }
}
